import 'dart:async';

import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 实现倒计时
  int _countdown = 3;
  bool _isCountingDown = false;
  Timer? _timer;

  // 手机号输入框控制器
  final _phoneController = TextEditingController();
  // 验证码输入框控制器
  final _codeController = TextEditingController();

  // 提交表单登录表
  _submit() async {
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号~');
    }
    if (_codeController.text.isEmpty) {
      return ToastUtil.showError('请输入验证码~');
    }
    if (!RegExp(r'^1\d{10}$').hasMatch(_phoneController.text)) {
      return ToastUtil.showError('手机号格式错误~');
    }
    if (!RegExp(r'^\d{6}$').hasMatch(_codeController.text)) {
      return ToastUtil.showError('验证码错误~');
    }

    final res = await http.post('/login', data: {
      'mobile': _phoneController.text,
      'code': _codeController.text,
    });
    if (res['code'] != 10000) {
      return ToastUtil.showError(res['message']);
    } else {
      ToastUtil.showSuccess(res['message']);
      TokenManager().saveToken(res['data']['token']);
      Navigator.pop(context);
      // 事件总线3；触发事件
      eventBus.fire(RefreshMine());
    }
  }

  // 倒计时
  _startCountdown() {
    // 如果已经处于倒计时状态，则不执行任何操作
    if (_isCountingDown) {
      return;
    }
    _isCountingDown = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isCountingDown = false;
          _countdown = 3;
          timer.cancel();
        }
      });
    });
  }

  // 获取验证码前，需要校验手机号
  _getVerificationCode() async {
    // 非空校验
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号~');
    }

    // 手机号正则表达式校验
    // RegExp reg = /^1\d{10}$/;
    RegExp reg = RegExp(r'^1\d{10}$');
    if (reg.hasMatch(_phoneController.text) == false) {
      return ToastUtil.showError('手机号格式错误~');
    }

    // 调用接口，发送验证码到用户手机
    final res = await http.get(
      '/code',
      params: {'mobile': _phoneController.text},
    );
    // 业务状态吗错误提示
    if (res['code'] != 10000) return ToastUtil.showError('获取验证码失败');

    // 模拟用户输入验证码，延迟2秒，输入验证码
    Future.delayed(const Duration(seconds: 2), () {
      _codeController.text = res['data']['code'];
    });

    // 请求发送成功后，才开启倒计时
    _startCountdown();
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController, // 文本编辑控制器，用于收集数据
                    keyboardType: TextInputType.phone, // 键盘类型
                    maxLength: 11, // 最大输入长度
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: _isCountingDown
                      ? null // 禁用状态
                      : () {
                          //
                          _getVerificationCode();
                        },
                  child: _isCountingDown
                      ? Text('$_countdown秒后重新获取')
                      : const Text('获取验证码'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController, // 文本编辑控制器，用于收集数据
              keyboardType: TextInputType.number, // 键盘类型
              maxLength: 6, // 最大输入长度
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _submit();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
